<template>
    <div class="withdraw-setting-info">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
            <el-form-item label="提现方式">
                <div class="checkbox-content">
                    <el-checkbox :disabled="isDisabled || !hasWeixinPay" v-model="form.toWechat">
                        提现至微信
                    </el-checkbox>
                    <div class="question-tip1">
                        <el-popover
                            placement="top"
                            :width="300"
                            trigger="hover"
                            effect="dark"
                            content="商家需要使用微信自有支付，且开通【商家转账到零钱】">
                            <template #reference>
                                <img class="icon-img" src="@/assets/imgs/sys/question-circle.png" />
                            </template>
                        </el-popover>
                        <span>(需开通【商家转账到零钱】)</span>
                    </div>
                    <div class="question-tip2" @click="handleHelp">
                        <img class="icon-img" src="@/assets/imgs/sys/question-circle_active.png" />
                        如何开通【商家转账到零钱】？
                    </div>
                </div>
                <div class="checkbox-content">
                    <el-checkbox v-model="form.toBankAccount">提现至银行卡</el-checkbox>
                    <div class="baofu-auth" v-if="form.toBankAccount">
                        <div class="switch-main">
                            <el-switch v-model="form.baofooAutoTransfer" :before-change="handleBeforeChange"></el-switch
                            ><span class="switch-tip">宝付账户自动打款</span>
                        </div>
                        <div v-if="!isAuthorized" class="baofu-auth-tip" @click="handleAuthorization">
                            <img class="icon-img" src="@/assets/imgs/sys/question_active.png" />
                            请先授权，委托平台从商家的宝付账户自动扣款
                        </div>
                        <div v-else class="baofu-auth-tip baofu-auth-success-tip">
                            <img class="icon-img" src="@/assets/imgs/sys/success.png" />
                            已授权平台自动扣款
                        </div>
                    </div>
                </div>
            </el-form-item>
            <div class="form-footer">
                <el-button :disabled="isDisabled" type="primary" @click="saveHandler">保存</el-button>
            </div>
        </el-form>
        <!-- todo:引入帮助页面欧阳的 -->
        <ZwPayHelper ref="helperRef" />
    </div>
</template>

<script setup>
import { ref, unref, reactive, computed, onMounted } from 'vue';
import request from '@/request';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { cloneDeep } from '@/commons/utils';
import store from '@/store/index';
import storage from '@/commons/storage';

const useAuth = store.useAuthStore();
const permissions = useAuth.permissions;
const isDisabled = computed(() => {
    return !permissions.has('withdraw_setting:edit');
});

const router = useRouter();

const formRef = ref();
const form = reactive({
    toWechat: false,
    toBankAccount: false,
    baofooAutoTransfer: false
});
const checkWay = (rule, value, callback) => {
    if (!form.toWechat && !form.toBankAccount) {
        return callback('请至少选择一种提现方式');
    }
    callback();
};
const rules = {
    way: [{ required: true, message: '请选择提现方式', validator: checkWay, trigger: 'change' }]
};

let hasWeixinPay = ref(true);

// 新增/编辑表单
const saveHandler = async () => {
    // todo:接口
    if (!unref(formRef)) return;
    await unref(formRef).validate(async (valid, fields) => {
        if (valid) {
            const _form = cloneDeep(form);
            const { code } = await request('withdrawSetting', _form);
            if (code !== 0) {
                return;
            }
            ElMessage({
                type: 'success',
                message: '保存成功'
            });
        } else {
            unref(formRef).scrollToField(Object.keys(fields)?.[0]);
        }
    });
};

const clearValidate = field => {
    unref(formRef).clearValidate(field);
};

const validateField = field => {
    unref(formRef).validateField(field);
};

// const handleChange = val => {
//     validateField('way');
// };

let isAuthorized = ref(false);
let thisAppId = ref('');
const handleAuthorization = async () => {
    // 调取接口
    // 请先开通宝付支付 499401 宝付支付尚未绑定小程序 499402 已授权 0 未授权 499403
    const { code, msg } = await request('authorizationEnable', { appId: thisAppId.value });
    // let code = 499402;
    // todo:弹窗或跳转
    if (code !== 0) {
        if (code == 499403) {
            // todo:授权落地页 data.url? returnUrl
            const { data, msg } = await request('authorizationUrl', {
                callType: 'SIGN_PAY_ENTRUST'
            });
            const redirectUrl = data?.redirectUrl;
            if (!redirectUrl) {
                ElMessage.error(msg);
                return;
            }
            window.location.href = redirectUrl + '?Address=' + window.location.href;
            return;
        }
        let msgText = msg;
        if (code == 499401) {
            msgText = '已开通宝付支付的商户，才可使用自动扣款功能';
        } else if (code == 499402) {
            msgText = '';
        } else {
            msgText = msg || '服务异常，请稍后重试';
        }
        const title = {
            499401: '请先开通宝付支付',
            499402: '宝付支付尚未绑定小程序'
        };
        const btns = {
            499401: '立即开通',
            499402: '立即绑定'
        };
        ElMessageBox.alert(msgText, title[code], {
            cancelButtonText: '下次再说',
            confirmButtonText: title[code] ? btns[code] : '关闭',
            center: true,
            showCancelButton: title[code] ? true : false,
            customClass: 'withdraw-setting-message',
            callback: async action => {
                if (action !== 'confirm') {
                    return;
                }
                if (code == 499401) {
                    // todo:跳转的宝付步骤路径，问小月亮
                    router.push({
                        path: '/pay/account'
                    });
                } else if (code == 499402) {
                    // todo:绑定小程序
                    const result = await request('bindSimIdServ', { appId: thisAppId.value });
                    if (![0, 4000003].includes(result.code)) {
                        ElMessage({
                            type: 'error',
                            message: result.msg
                        });
                        return;
                    }
                    hasAuthorized();
                } else {
                }
            }
        });
        return;
    }
    ElMessage({
        type: 'success',
        message: '已经授权'
    });
    // hasAuthorized();
    isAuthorized.value = true;
};
const hasAuthorized = async () => {
    try {
        const { code } = await request('authorizationEnable', { appId: thisAppId.value });
        isAuthorized.value = code === 0;
    } catch (error) {
        ElMessage({
            type: 'error',
            message: error?.msg || '系统异常'
        });
    }
};

const helperRef = ref(null);
const handleHelp = () => {
    // 打开帮助弹窗，tab默认为6
    helperRef?.value.onOpen(6);
};

const handleBeforeChange = val => {
    if (!form.baofooAutoTransfer) {
        // 校验是否授权
        if (!isAuthorized.value) {
            ElMessage({
                type: 'error',
                message: '请先授权'
            });
            return false;
        }
        return true;
    }
    return true;
};

const getDetail = async () => {
    const { data } = await request('withdrawSettingInfo');
    const _data = data || {};
    Object.keys(form).map(key => {
        form[key] = _data[key];
    });
    // Object.assign(form, _data);
};

const getWeixinPay = async () => {
    // const { data } = await request('paymentChannelList', {
    //     tenantId: storage.get('ZW-TENANT-ID'),
    //     payChannel: 'WECHAT'
    // });
    // hasWeixinPay.value = !!(data || {})?.list?.find(item => item.channelCode === 'WECHAT' && item.paymentId > 0);
    const { data } = await request('wechatPayConfig');
    hasWeixinPay.value = data?.isWechatPayConfig;
};

const geyWeixinInfo = async () => {
    const { data } = await request('miniappAppid');
    thisAppId.value = data?.authorizerAppid;
};

onMounted(async () => {
    getDetail();
    await geyWeixinInfo();
    hasAuthorized();
    getWeixinPay();
});
</script>

<style lang="scss">
.withdraw-setting-info {
    .w420 {
        width: 420px;
    }
}
.withdraw-setting-message {
    width: 350px;
    .el-message-box__title {
        justify-content: flex-start;
    }
    .el-message-box__content {
        padding-top: 20px;
        padding-bottom: 20px;
        /* text-align: left; */
    }
    .el-message-box__btns {
        .el-button {
            width: 140px;
            margin-bottom: 10px;
        }
    }
}
</style>
<style lang="scss" scoped src="./index.scss"></style>
